<template>
  <div class="login-container">
    <!-- 背景图 -->
    <div class="background-image"></div>

    <!-- 登录表单 -->
    <div class="login-box">
      <h2 class="system-title">铁运无人机智能巡检系统</h2>

      <div class="login-form">
        <div class="form-title">
          <span class="title-ch">用户登录</span>
          <span class="title-en">USER LOGIN</span>
        </div>

        <el-form @submit.prevent="onSubmit" :model="form" ref="formRef">
          <el-form-item :error="errors.username">
            <el-input
              v-model="form.username"
              placeholder="请输入用户名称"
              size="large"
              :prefix-icon="User"
            />
          </el-form-item>

          <el-form-item :error="errors.password">
            <el-input
              v-model="form.password"
              placeholder="请输入登录密码"
              size="large"
              type="password"
              show-password
              :prefix-icon="Lock"
            />
          </el-form-item>

          <div class="remember-box">
            <input v-model="form.rememberMe" type="checkbox" id="rememberMe" />
            <label for="rememberMe">记住密码</label>
          </div>

          <el-button type="primary" class="login-button" @click="onSubmit" round>登录</el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import { useAuthStore } from '@/stores/user'
import { useAlarmStore } from '@/stores/alarmNum'

const router = useRouter()
const authStore = useAuthStore()
const alarmStore = useAlarmStore()

const form = ref({
  username: '',
  password: '',
  rememberMe: false
})
const errors = ref({
  username: '',
  password: ''
})

onMounted(() => {
  const savedUsername = localStorage.getItem('username')
  const savedPassword = localStorage.getItem('password')
  if (savedUsername && savedPassword) {
    form.value.username = savedUsername
    form.value.password = savedPassword
    form.value.rememberMe = true
  }
})

const validate = () => {
  errors.value.username = form.value.username ? '' : '请输入用户账号'
  errors.value.password = form.value.password ? '' : '请输入登录密码'
  return !errors.value.username && !errors.value.password
}

const onSubmit = async () => {
  if (!validate()) return

  try {
    const res = await request.post('/user/login', {
      username: form.value.username,
      password: form.value.password
    })

    if (res.data) {
      const userData = res.data.user

      if (userData.status === 'S') {
        if (form.value.password === 'ruibo@520') {
          router.push({
            path: '/changePassword',
            query: { 
                userData: JSON.stringify(userData) // 转为字符串传递
            }
          })
          return
        }

        if (form.value.rememberMe) {
          localStorage.setItem('username', form.value.username)
          localStorage.setItem('password', form.value.password)
        }

        localStorage.setItem('isLoggedIn', 'true')
        authStore.setAuthData(res.data)
        await alarmStore.fetchTotalAlarms()

        await request.post('/user/insertOperation', {
          username: userData.username,
          name: userData.name,
          organizationID: res.data.organizationID || '',
          ip: null,
          operationModel: '登录成功',
          operationResult: '用户登录成功',
          operationTime: null,
          operationType: 'login'
        })

        router.push('/home')
      } else {
        ElMessage.error('该账号已被禁用，请联系管理员')
      }
    } else {
      ElMessage.error('账号或密码错误')
    }
  } catch (e) {
    ElMessage.error('登录失败，请检查网络')
    console.error(e)
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  width: 100vw;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('https://cdn.pixabay.com/photo/2023/09/12/10/21/mountains-8248538_1280.jpg');
  background-size: cover;
  background-position: center;
  filter: brightness(0.7);
  z-index: 0;
}

.login-box {
  z-index: 1;
  background-color: rgba(255, 255, 255, 0.94);
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.2);
  width: 340px;
  max-width: 90%;
  text-align: center;
}

.system-title {
  font-size: 20px;
  color: #333;
  margin-bottom: 24px;
  font-weight: bold;
}

.form-title {
  font-size: 16px;
  margin-bottom: 24px;
  color: #2a91ff;
}

.title-ch {
  font-weight: bold;
  margin-right: 6px;
}

.title-en {
  font-size: 12px;
  color: #666;
}

.remember-box {
  margin: 10px 0 20px 0;
  font-size: 13px;
  text-align: left;
}

.login-button {
  width: 100%;
  height: 38px;
  font-size: 15px;
}
</style>
